package com.coldchain.auth.module.client.service.impl;

import com.coldchain.auth.feign.IUserService;
import com.coldchain.auth.jwt.user.JwtAuthenticationRequest;
import com.coldchain.auth.jwt.user.JwtTokenUtil;
import com.coldchain.auth.module.client.bean.LoginTypeEnum;
import com.coldchain.auth.module.client.service.IAuthService;
import com.coldchain.common.auth.AuthUser;
import com.coldchain.common.exception.auth.UserInvalidException;
import com.coldchain.common.msg.ObjectRestResponse;
import com.coldchain.common.redis.RedisUtils;
import com.coldchain.common.util.RedisKeyUtil;
import com.fangliai.core.constants.CommonConstants;
import com.fangliai.core.util.jwt.IJWTInfo;
import com.fangliai.core.util.jwt.JWTInfo;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 提拱用户认证功能服务
 * @ClassName IAuthServiceImpl

 * @Author fangliai
 * @Date 2018/8/29 9:17
 * @Vesion 1
**/
@Service
public class IAuthServiceImpl implements IAuthService {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisUtils redisUtils;
    @Override
    public String login(JwtAuthenticationRequest authenticationRequest) throws Exception {
        AuthUser user =null;
        switch (LoginTypeEnum.valueOf(authenticationRequest.getLoginType())){
            case PASSWORD:
                 ObjectRestResponse<AuthUser> restResponse=userService.validatePassword(authenticationRequest.getScope(),authenticationRequest.getUsername(), authenticationRequest.getPassword());
                  if(restResponse.getData()==null){
                        throw new UserInvalidException(restResponse.getMessage());
                 }
                 user=restResponse.getData();
                 break;
            case SSM:
                break;
            default:
                break;
        }

        String token = "";
        Map<String, String> map = new HashMap<>();
        if(!StringUtils.isEmpty(user.getCysId())){
            map.put(CommonConstants.JWT_KEY_CYS_ID, String.valueOf(user.getCysId()));
        }
        if(!StringUtils.isEmpty(user.getCommpanyId())){
            map.put(CommonConstants.JWT_KEY_COMMPANY_ID, String.valueOf(user.getCommpanyId()));
        }
        map.put(CommonConstants.JWT_KEY_SYS_MODEL, String.valueOf(user.getSysModel()));
        JWTInfo jwtInfo = new JWTInfo(StringUtils.isEmpty(user.getUserName())?user.getUserId():user.getUserName(), user.getUserId(), StringUtils.isEmpty(user.getNickName())?"":user.getNickName());
        Date expireTime = DateTime.now().plusSeconds(jwtTokenUtil.getExpire()).toDate();
        token = jwtTokenUtil.generateToken(jwtInfo, map, expireTime);

        redisUtils.getRBucket(RedisKeyUtil.buildUserAbleKey(jwtInfo.getId(), expireTime)).set("1");
        return token;
    }

    @Override
    public String refresh(String oldToken) throws Exception {
        IJWTInfo infoFromToken = jwtTokenUtil.getInfoFromToken(oldToken);
        invalid(oldToken);
        Date expireTime = DateTime.now().plusSeconds(jwtTokenUtil.getExpire()).toDate();
        // 刷新用户的token到redis中
        redisUtils.getRBucket(RedisKeyUtil.buildUserAbleKey(infoFromToken.getId(), expireTime)).set("1");
        return jwtTokenUtil.generateToken(infoFromToken, infoFromToken.getOtherInfo(), expireTime);

    }

    @Override
    public void validate(String token) throws Exception {
        jwtTokenUtil.getInfoFromToken(token);
    }

    @Override
    public Boolean invalid(String token) throws Exception {
        IJWTInfo infoFromToken = jwtTokenUtil.getInfoFromToken(token);
        redisUtils.getRBucket(RedisKeyUtil.buildUserAbleKey(infoFromToken.getId(), infoFromToken.getExpireTime())).delete();
        redisUtils.getRBucket(RedisKeyUtil.buildUserDisableKey(infoFromToken.getId(), infoFromToken.getExpireTime())).set("1");
        return true;
    }



 }
